<?php

namespace Tyrone\Lib;


class BaseWorker
{
    protected $sDate;
    protected $eDate;
    protected $config = [];
    protected $MysqlPool;
    protected $RedisPool;
    protected $worker_id;
    protected $conf;

    public function loadBaseFile($conf=[]){
        self::register();
        $this->conf = $conf;
        require_once DIR.'/vendor/autoload.php';
        require_once DIR.'/data/config.php';
        require_once DIR.'/helper.php';
    }


    public function __construct($sDate=null,$eDate=null)
    {
        $sDate && $this->sDate = $sDate;
        $eDate && $this->eDate = $eDate;
    }

    public function isRunCenterCrontab($worker_id){
        return (GROUP==1 && $worker_id===0);
    }

    public static function register()
    {
        //set_error_handler([__CLASS__, 'appError']);
        //set_exception_handler([__CLASS__, 'appException']);
        register_shutdown_function([__CLASS__, 'appShutdown']);
    }

    public static function appShutdown()
    {
        $error = error_get_last();

        if (isset($error['type']) && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR]))
        {
            $e = new \ErrorException($error['message'], 0, 1, $error['file'], $error['line']);
            throw $e;
        }
    }




    public function creatMysqlPool($conf,$key = 'mysql',$num=1){
        $config = $conf[$key];
        return new \Tyrone\Lib\DatabasePool($config, $num,['debug'=>APP_DEBUG]);
    }
    public function creatRedisPool($conf,$num=1){
        $config = $conf['redis'];
        return new \Swoole\Database\RedisPool((new \Swoole\Database\RedisConfig)
            ->withHost($config['host'])
            ->withPort($config['port'])
            ->withAuth($config['password'])
            ->withDbIndex($config['database'])
            ->withTimeout(5)
        ,$num);
    }

    public function creatRedis($conf){
        $config = $conf['redis'];
        $redis = new \Swoole\Coroutine\Redis();
        $redis->connect($config['host'], $config['port']);
        $redis->auth($config['password']);
        $redis->select($config['database']);
        return $redis;
    }
}